#from the class `x' import everything

import random
from card import *
from deck import *
from player import *
from server_send_and_receive_test import *

#main class
class Game(object):
    def __init__(self):
        #declaring pipe
        self.pipe = ServerPipe("",10001)
        #player list (empty list)
        self.playerList = []
        #player1(emptry list)
        self.ip = None
        self.port = None
        self.state = "NEW"

        #test deck for reading data list
        #self.cardfile = cardfile
        #self.T_deck = None
        #create player list
        #self.players = []
        self.buildDecks()
        self.stack=[]
##-----------------------##
##--------Set up 2 connections-------##
    def setupConnection(self,ip,port):
        self.ip = ip
        self.port = port
        #Somebody set us up the pipe

    def startConn(self):
        #if self.ip == None:
        #    print "ip not set"
        #    return
        #else:
        #self.pipe.closeConnection()
        self.pipe.startConnection(self.ip,self.port)
        #self.pipe.setPlayerInfo()
        self.pipe.recvData()
         

##------get 2 players----------------##
#check to see how many players are currently in the game, if there is only 1 the game will add another,
#if there is more than 2 players the game will inform the server of this

    # def checkPlayers(self):      
    #     if len(self.playerList) == 1 :
    #         print "Needs 1 more...Adding player:"
    #     #TODO: set a function to ask the game for a new player rather than just adding a new one
    #         game.addPlayer("Tester",11,34,None)
    #         print "There is now two players in this game"
    #     elif len(self.playerList) == 2:
    #         print "There are two players in this game"
    #     else:
    #     #TODO: needs a function to remove the last player or start again
    #         print "Too many players in this game"
            
    def addPlayer(self,name,ID,score,deck):        
        #TODO: Check we don't already have two players
        self.playerList.append(Player(name,ID,score))
            
    def printPlayers(self):
        print self.playerList
    

##------build decks-------------------##        
#Function that creates 3 instances of the `Deck' object and populates them with items
#-- To do --/ Change buildDecks function to read card info from data file and populate list 
    def buildDecks(self):
        #decks.buildNewDecks()
        #build Hazard deck and populate with cards using the information from `hazarCardsContent.csv'
        #file in the /data folder. (open file>>set range (number of cards)>>read each line>>append to list)
        self.H_deck=Deck("Hazard")
        f = open('../data/hazardCardsContent.csv')
        for i in range (1,27):
            line = f.readline()
            items = line.split("#")
            self.H_deck.append(Hazard(items[0],items[1],items[2]))
            #self.H_deck.append(Card("hz%d"%i,"hazard%d"%i,"H/%d"%i))
#----> print code# #print self.H_deck.cards[i-1].shortTitle

        #print "New Deck"

        #build Action deck and populate with cards using the information from `actionCardsContent.csv'
        #file in the /data folder. (open file>>set range (number of cards)>>read each line>>append to list
        self.A_deck=Deck("Action")
        f = open('../data/actionCardsContent.csv')
        for i in range (1,28):
            line = f.readline()
            items = line.split('#')
            self.A_deck.append(Action(items[0],items[1],items[2]))
             #self.A_deck.append(Card("act%d"%i, "Action%d"%i, "A/%d"%i))
#---> print code# #print self.A_deck.cards[i-1].shortTitle

        #print "New Deck"

        #Situation cards require .csv file to be created for them    
        self.S_deck=Deck("Situation")
        f = open('../data/situationCardsContent.csv')
        for i in range (1,9):
            line = f.readline()
            items = line.split('#')
            self.S_deck.append(Situation(items[0],items[1],items[2]))
            #self.S_deck.append(Card("sit%d"%i, "Situation%d"%i, "S/%d"%i))
#---> print code# # print self.S_deck.cards[i-1].shortTitle


        
## All .csv files were copied and tweaked from those used to create
## the physical cards, card class attributes had to be cut down
## because `#' was used to break up the descriptions for the cards,
## however we do not need them here.


##------allocate cards---------------##

    def popR(self, deck):

        try:
            s=random.randint(0,len(deck)-1)
            return deck.pop(s)
        except IndexError:
            raise Exception("Cannot popR - There are no more cards in the deck!")
      
    def dealCards(self):
        #get cards from the H and A decks and put them in
        #the deck list inside playerList(Player)

        #Hazards

        
        if len(self.playerList) == 2:
            for i in range(4):
                for p in self.playerList:
                    p.hDeck.append(self.popR(self.H_deck))
                    p.aDeck.append(self.popR(self.A_deck))
        else:
            raise Exception("A game cannot be started without two players")

        
        #Actions
#        if self.pAmount == 2:
#            for i in range(4):
#                for p in self.playerList:
#                    p.aDeck.append(self.popR(self.A_deck))
#        else:
#            print "you need 2 players to start"
            
          
     

##------set Sit card-----------------##

    def pickSitCard(self):

       
        picked=self.popR(self.S_deck)
        return picked
            
        #TODO: Re-work to use the popR function
        #  sit = random.randrange(0,7)
        #  print sit 
        #  self.S_deck.pop(sit)
        #  print self.S_deck.cards#.shortTitle
        #put in loop to pick again if number selected has alread been removed
        

    def sendAll(self,message):
        for p in self.playerList:
            p.connection.sendall(message)

##-------set state-------------------##
    def stateStep(self):
        if self.state == "NEW":
            if len(self.playerList) == 2:
                self.state = "W_P1_S"
                print "Got two players."
                self.sendAll("The game begins")
            else:
                print "You need 2 players to start a game"
                
        elif self.state == "W_P1_S":
            print "Waiting for player 1 to play situation card"
            #send state to clients and wait for P1 to choose card
            self.stack.append(self.pickSitCard())
            print "Player 1 has played card..."
            self.sendAll("Player 1 has played the situation card %s"%str(self.stack[0]))
            #Send message to players
            self.state = "W_P2_H"

        elif self.state == "W_P2_H":
            #Check player 2's pipe to see if it's been played.  If it has, change state
            pass
            
        elif self.state == "W_P1_A":
            #check pipe...
            pass
        # if self.state == "P1 PLAYS ACTION":
        #     #send state to clients and calculate round scores
        #     #get scores
        #     #move state on by playing P2's sit card
        #     print "End of round, <scores> starting new round..."
        #     game.pickSitCard()
        #     self.state = "P2 PLAYS SIT"
        #     print "Player 2 has played card..."
        # else:
        #     self.state = "P1 PLAYS ACTION"

        # if self.state == "P2 PLAYS SIT":
        #     #send state to clients and wait for P1 to choose card
        #     #determine if player 1 has played hazard card
        #     if self.state == "P1 PLAYS HAZARD":
        #         print "Player 2 has played a hazard card"
        #     else:
        #         self.state = "P2 PLAYS SIT"
        #         print "Waiting for player 1 to play Hazard card"

        # if self.state == "P1 PLAYS HAZARD":
        #     #send state to clients and wait for P2 to choose card
        #     #determine if player 2 has played action card
        #     if self.state == "P2 PLAYS ACTION":
        #         print "Player 2 has played an action card"
        #     else:
        #         self.state = "P1 PLAYS HAZARD"
        #         print "Waiting for player 2 to play an Action card"

        # if self.state == "P2 PLAYS ACTION":
        #     #send state to clients and calculate round scores
        #     #get scores
        #     #check if there are any situation cards left
        #     if len(self.S_deck) == "0":
        #         self.state = "GAME OVER"
        #         print "Game over"
        #         print "Scores are..."
        #     else:
        #         #move state on by playing P1's sit card
        #         "End of round, <scores> starting new round..."
        #         game.pickSitCard()
        #         self.state = "P1 PLAYS SIT"
        
        
            
            

##-------listen for player move------##



##------update deck/score/state------##


##------------------------##
#test function
#        def getCards(self,cardfile):
#            self.cardfile = cardfile
#            self.T_deck=Deck("Test Deck")
#            f = open(cardfile)
#            for l in f:
#                items=l[:-1].split(",")
#                self.T_deck[(items[0],items[1])]=float(items[2])
#            f.close()
#A function to check how many players there are, (its fucking impossible)
    #def checkPlayer(self):

     
##-------------------------##
##-------------------------##
                            
if __name__ == "__main__":
    game = Game()
    # print empty lists
    # print game.H_deck
    # print game.A_deck
    # print game.S_deck
    #run `buildDecks function




    game.addPlayer("Test",21,34,None)
    game.addPlayer("Tester",11,34,None)
   # game.addPlayer("Testeds",14,74,None)
    
    game.dealCards()
    for i in game.playerList: print i
    game.pickSitCard()
    game.state()
    
#  #   print game.H_deck
#  #   print game.A_deck
#  #   print game.S_deck


# #    game.checkPlayer() 
# #    game.getCards("../data/HazardCardInfo.cvs")


    
    ip = ""
    port = 1234

   

# #-Connection#    game.setupConnection('127.0.0.1',10001)
# #-Connection#    game.startConn()

#     game.dealCards()

# #   game.printPlayers()
# #    game.addPlayer(pipe.dataList)
